package com.ys.service.advanced.Impl;


import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.*;
import com.ys.config.MyConfig;
import com.ys.entity.advanced.*;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAmazonShopExchangeRate;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.advanced.MarketplaceEnum;
import com.ys.enume.advanced.CampaignStatusEnum;
import com.ys.enume.advanced.ReportTypeEnum;
import com.ys.mapper.advanced.*;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.advanced.AdsSpServise;
import com.ys.service.log.ApiLogService;
import com.ys.util.ApiHttpUtils;
import com.ys.util.RedisUtil;
import com.ys.util.dhecp.StringUtils;
import com.ys.vo.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

/**
 * 亚马逊广告api
 */
@Service("adsSpServise")
public class AdsSpServiseImpl implements AdsSpServise {


    @Autowired
    private AdsReportLogMapper adsReportLogMapper;

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DiySqlMapper diySqlMapper;

    @Autowired
    private AdsSpPurchasedProductMapper  adsSpPurchasedProductMapper;

    /**
     * 广告活动预算表
     * @return
     */
    @Override
    public ApiResponse getSpCampaigns(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
                                   ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spCampaigns");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("campaign");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("campaignId");
        columnsList.add("campaignName");
        columnsList.add("campaignStatus");
        columnsList.add("campaignBudgetCurrencyCode");
        columnsList.add("campaignBudgetAmount");
        columnsList.add("campaignBiddingStrategy");
        columnsList.add("impressions");
        columnsList.add("clicks");
        columnsList.add("clickThroughRate");
        columnsList.add("cost");
        columnsList.add("spend");
        columnsList.add("costPerClick");
        columnsList.add("unitsSoldClicks1d");
        columnsList.add("sales1d");
        columnsList.add("purchases1d");
        columnsList.add("unitsSoldSameSku1d");
        columnsList.add("attributedSalesSameSku1d");
        columnsList.add("purchasesSameSku1d");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }

    /**
     * 广告位报表
     * @return
     */
    @Override
    public ApiResponse getSpCampaignsWithPlacement(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
            ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spCampaigns");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("campaign");
        groupByList.add("campaignPlacement");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("campaignId");
        columnsList.add("campaignName");
        columnsList.add("campaignStatus");
        columnsList.add("placementClassification");
        columnsList.add("campaignBudgetCurrencyCode");
        columnsList.add("campaignBudgetAmount");
        columnsList.add("campaignBiddingStrategy");
        columnsList.add("impressions");
        columnsList.add("clicks");
        columnsList.add("clickThroughRate");
        columnsList.add("cost");
        columnsList.add("spend");
        columnsList.add("costPerClick");
        columnsList.add("unitsSoldClicks1d");
        columnsList.add("sales1d");
        columnsList.add("purchases1d");
        columnsList.add("unitsSoldSameSku1d");
        columnsList.add("attributedSalesSameSku1d");
        columnsList.add("purchasesSameSku1d");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }

    /**
     * 广告组投放表
     * @return
     */
    @Override
    public ApiResponse getSpTargeting(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
            ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spTargeting");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("targeting");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("portfolioId");
        columnsList.add("campaignId");
        columnsList.add("campaignName");
        columnsList.add("adGroupId");
        columnsList.add("adGroupName");
        columnsList.add("campaignBudgetCurrencyCode");
        columnsList.add("keywordId");
        columnsList.add("keyword");
        columnsList.add("keywordType");
        columnsList.add("impressions");
        columnsList.add("clicks");
        columnsList.add("clickThroughRate");
        columnsList.add("cost");
        columnsList.add("costPerClick");
        columnsList.add("unitsSoldClicks1d");
        columnsList.add("sales1d");
        columnsList.add("purchases1d");
        columnsList.add("unitsSoldSameSku1d");
        columnsList.add("attributedSalesSameSku1d");
        columnsList.add("purchasesSameSku1d");
        columnsList.add("unitsSoldOtherSku7d");
        columnsList.add("salesOtherSku7d");
        columnsList.add("topOfSearchImpressionShare");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }


    /**
     * 广告组搜索词表
     * @return
     */
    @Override
    public ApiResponse getSpSearchTerm(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
            ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spSearchTerm");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("searchTerm");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("portfolioId");
        columnsList.add("campaignId");
        columnsList.add("campaignName");
        columnsList.add("adGroupId");
        columnsList.add("adGroupName");
        columnsList.add("campaignBudgetCurrencyCode");
        columnsList.add("searchTerm");
        columnsList.add("keywordId");
        columnsList.add("keyword");
        columnsList.add("keywordType");
        columnsList.add("impressions");
        columnsList.add("clicks");
        columnsList.add("clickThroughRate");
        columnsList.add("cost");
        columnsList.add("costPerClick");
        columnsList.add("acosClicks7d");
        columnsList.add("roasClicks7d");
        columnsList.add("unitsSoldClicks1d");
        columnsList.add("sales1d");
        columnsList.add("purchases1d");
        columnsList.add("unitsSoldSameSku1d");
        columnsList.add("attributedSalesSameSku1d");
        columnsList.add("purchasesSameSku1d");
        columnsList.add("unitsSoldOtherSku7d");
        columnsList.add("salesOtherSku7d");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }

    /**
     * 广告商品表
     * @return
     */
    @Override
    public ApiResponse getSpAdvertisedProduct(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
            ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spAdvertisedProduct");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("advertiser");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("portfolioId");
        columnsList.add("campaignId");
        columnsList.add("campaignName");
        columnsList.add("adGroupId");
        columnsList.add("adGroupName");
        columnsList.add("campaignBudgetCurrencyCode");
        columnsList.add("adId");
        columnsList.add("advertisedAsin");
        columnsList.add("advertisedSku");
        columnsList.add("impressions");
        columnsList.add("clicks");
        columnsList.add("clickThroughRate");
        columnsList.add("cost");
        columnsList.add("spend");
        columnsList.add("costPerClick");
        columnsList.add("acosClicks7d");
        columnsList.add("roasClicks7d");
        columnsList.add("unitsSoldClicks1d");
        columnsList.add("sales1d");
        columnsList.add("purchases1d");
        columnsList.add("unitsSoldSameSku1d");
        columnsList.add("attributedSalesSameSku1d");
        columnsList.add("purchasesSameSku1d");
        columnsList.add("unitsSoldOtherSku7d");
        columnsList.add("salesOtherSku7d");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }


    /**
     * 非广告商品订单情况表
     * @return
     */
    @Override
    public ApiResponse getSpPurchasedProduct(TpAmazonShop tpAmazonShop, Profiles profiles, Map<String, String> paramsHerder, JSONObject jsonObjectOb
            ,String date,Integer reportType) {
        ApiResponse apiResponse = new ApiResponse();
        paramsHerder.put("Amazon-Advertising-API-Scope",profiles.getProfileId());
        paramsHerder.put("Content-Type","application/vnd.createasyncreportrequest.v3+json");
        //设置body
        Configuration configuration = new Configuration();
        configuration.setAdProduct("SPONSORED_PRODUCTS");
        configuration.setReportTypeId("spPurchasedProduct");
        configuration.setFormat("GZIP_JSON");
        configuration.setTimeUnit("DAILY");
        List<String> groupByList = new ArrayList<>();
        groupByList.add("asin");
        configuration.setGroupBy(groupByList);
        List<String> columnsList = new ArrayList<>();
        columnsList.add("date");
        columnsList.add("adGroupId");
        columnsList.add("adGroupName");
        columnsList.add("advertisedSku");
        columnsList.add("advertisedAsin");
        columnsList.add("purchasedAsin");
        columnsList.add("unitsSoldOtherSku1d");
        columnsList.add("salesOtherSku1d");
        columnsList.add("purchasesOtherSku1d");
        configuration.setColumns(columnsList);
        ReportsRquest reportsRquest = new ReportsRquest();
        reportsRquest.setConfiguration(configuration);
        reportsRquest.setEndDate(date);
        reportsRquest.setStartDate(date);
        reportsRquest.setName("Report");
        String result = ApiHttpUtils.sendPostBody(jsonObjectOb.get("amazonApiUrlGg").toString()+"/reporting/reports", JSONObject.toJSONString(reportsRquest),paramsHerder);
        apiResponse = addAdsReportLog(result,apiResponse,tpAmazonShop,profiles,date,reportType);
        return apiResponse;
    }

    private ApiResponse addAdsReportLog( String result,ApiResponse apiResponse,TpAmazonShop tpAmazonShop, Profiles profiles,String date,Integer reportType){
        AdsReportLog adsReportLog = new AdsReportLog();
        if (result.equals(400)){
            apiResponse.setCode(400);
            apiResponse.setMessage("获取亚马逊获取报告失败,店铺信息=" + tpAmazonShop.getShopName());
            return apiResponse;
        }else {
            try {
                JSONObject jsonObject1 = JSON.parseObject(result);
                String reportId = String.valueOf(jsonObject1.get("reportId"));
                //新增报告记录数据
                adsReportLog.setReportId(reportId);
                adsReportLog.setProfileId(profiles.getProfileId());
                adsReportLog.setDate(date);
                adsReportLog.setShopId(String.valueOf(tpAmazonShop.getId()));
                adsReportLog.setShopName(tpAmazonShop.getShopName());
                adsReportLog.setReportType(reportType);
                adsReportLogMapper.insert(adsReportLog);
            }catch (Exception e){
                apiResponse.setCode(400);
                apiResponse.setMessage("获取亚马逊获取报告失败,新增报告记录失败,店铺信息=" + tpAmazonShop.getShopName()+
                        ",reportId = " +adsReportLog.getReportId() + ",profiles = " + profiles.getProfileId());
                return apiResponse;
            }
        }
        return apiResponse;
    }

    @Override
    public ApiResponse getReports(JSONObject jsonObjectOb, Map<String, String> getMapParams , AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        ApiResponse apiResponse = new ApiResponse();
        try {
            String errorGet;
            String url = "";
            String result = "";
            redisUtil.set(adsReportLog.getReportId(),String.valueOf(0));
            while (true) {
                errorGet = "";
                Thread.sleep(Long.parseLong(redisUtil.get(adsReportLog.getReportId())));
                JSONObject jsonObject = ApiHttpUtils.sendHttpClientGet(jsonObjectOb.get("amazonApiUrlGg").toString() + "/reporting/reports/" + adsReportLog.getReportId(), getMapParams);
                if (jsonObject != null) {
                    if (jsonObject.containsKey("error")) {
                        errorGet = jsonObject.getString("error");
                    }
                    if (StringUtils.isEmpty(errorGet)) {
                        JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                        if (data.get("status").equals("PENDING")) {
                            Integer redis = 0;
                            if(redisUtil.get(adsReportLog.getReportId())!= null && !redisUtil.get(adsReportLog.getReportId()).equals("")) {
                                redis = Integer.valueOf(redisUtil.get(adsReportLog.getReportId()));
                            }
                            redisUtil.set(adsReportLog.getReportId(),String.valueOf(redis+1000));
                            Thread.sleep(Long.parseLong(redisUtil.get(adsReportLog.getReportId())));
//                            continue;
                        }else {
                            if (data.get("url") != null) {
                                apiLogService.addApiLog("Amazon", "getProfiles1", data.get("createdAt").toString(),data.get("generatedAt").toString(),400,"");
                                Response httpResponse = null;
                                try {
                                    url = String.valueOf(data.get("url"));
                                    OkHttpClient httpclient = new OkHttpClient();
                                    httpclient.setConnectTimeout(30, TimeUnit.SECONDS);
                                    httpclient.setReadTimeout(30, TimeUnit.SECONDS);
                                    httpclient.setWriteTimeout(30, TimeUnit.SECONDS);
                                    Request request = new Request.Builder()
                                            .url(url)
                                            .get()
                                            .build();
                                    httpResponse = httpclient.newCall(request).execute();
                                }catch (Exception e){
                                    System.out.println("httpclient = " + e.getMessage());
                                }
                                if (!httpResponse.isSuccessful()) {
                                    result = "获取亚马逊单个店铺["+ jsonObjectOb.get("shopUser").toString()  + "-" + jsonObjectOb.get("shopName").toString() + "]" +"报表信息出错，其中report对象值为"+ JSON.toJSONString(data)+"，具体错误为下载报表文件地址["+url+"]出错，出错码为：" + httpResponse.code()+ "错误信息为："+httpResponse.message();
                                    apiResponse.setCode(500);
                                    apiResponse.setMessage(result);
                                    return apiResponse;
                                }
                                try (ResponseBody responseBody = httpResponse.body()) {
                                    try {
                                        InputStream inputStream = responseBody.byteStream();
                                        inputStream = new GZIPInputStream(inputStream);
                                        byte[] zipBytes = ZipUtil.unGzip(inputStream);
                                        String filePath = MyConfig.getProfile() + "/amazonreport/adssp/"+adsReportLog.getDate().replace("-", "");
                                        String gzOutPath =  filePath + "/adssp_report_" + adsReportLog.getReportId();
                                        File gzOutFileObj= new File(gzOutPath);
                                        if(!gzOutFileObj.exists()){
                                            gzOutFileObj.mkdirs();
                                        }
                                        String gzFileNamePrefix = "salestraffic_report_" + adsReportLog.getReportId();
                                        String fileName = gzFileNamePrefix +".txt";
                                        //将文件解压到gzOutPath目录中
                                        File gzOutFile = new File(gzOutPath + "/"+fileName);
                                        FileOutputStream fileOutputStream = new FileOutputStream(gzOutFile);
                                        fileOutputStream.write(zipBytes);
                                        fileOutputStream.close();
                                        File[] txtFileList = gzOutFileObj.listFiles();
                                        InputStream txtInputStream = null;
                                        StringBuffer txtStringBuffer = null;
                                        BufferedReader txtBufferedReader = null;
                                        if (txtFileList != null && txtFileList.length  > 0){
                                            for (File txtFileItem : txtFileList) {
                                                txtInputStream = new FileInputStream(txtFileItem);
                                                String txtLine; // 用来保存每行读取的内容
                                                txtStringBuffer = new StringBuffer();
                                                txtBufferedReader = new BufferedReader(new InputStreamReader(txtInputStream));
                                                txtLine = txtBufferedReader.readLine(); // 读取第一行
                                                while (txtLine != null) { // 如果 line 为空说明读完了
                                                    txtStringBuffer.append(txtLine); // 将读到的内容添加到 buffer 中
                                                    txtStringBuffer.append("\n"); // 添加换行符
                                                    txtLine = txtBufferedReader.readLine(); // 读取下一行
                                                }
                                                if(txtBufferedReader != null) txtBufferedReader.close();
                                                if(txtInputStream != null) txtInputStream.close();
                                                String txtContent = txtStringBuffer.toString();
                                                if (!StringUtils.isEmpty(txtContent)) {
                                                    JSONArray jsonArray = JSON.parseArray(txtContent);
                                                    if (jsonArray.size() != 0) {
//                                                        //广告活动预算表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.SPCAMPAIGNS.getNum())){
                                                            apiResponse = addAdsCampaigns(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        //广告位报表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.WithPlacement.getNum())){
                                                            apiResponse = addAdsCampaignsPlacement(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        //广告组投放表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.TARGETING.getNum())){
                                                            apiResponse = addAdsTargeting(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        //广告组搜索词表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.SEARCHTERM.getNum())){
                                                            apiResponse = addAdsSearchTerm(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        //广告商品表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.ADVERTISEDPRODUCT.getNum())){
                                                            apiResponse = addAdsAdvertisedProduct(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        //非广告商品订单情况表
                                                        if (adsReportLog.getReportType().equals(ReportTypeEnum.PURCHASEDPRODUCT.getNum())){
                                                            apiResponse = addAdsPurchasedProduct(jsonArray, apiResponse, jsonObjectOb,adsReportLog,thrOperateCompanyApply);
                                                            if (apiResponse.getCode() == 400){
                                                                return apiResponse;
                                                            }
                                                        }
                                                        apiResponse.setCode(0);
                                                    }
                                                }
                                                //添加数据结束删除文件
//                                                gzOutFile.delete();
                                            }
                                        }

                                    }catch (Exception ex){
                                        result = "获取亚马逊单个店铺["+ jsonObjectOb.get("shopUser").toString()  + "-" + jsonObjectOb.get("shopName").toString() + "]报表信息出错，其中report对象值为"+ JSON.toJSONString(data)+"，具体错误为下载报表文件地址["+url+"]出错";
                                        apiResponse.setCode(400);
                                        apiResponse.setMessage(result);
                                        return apiResponse;
                                    }
                                }catch (Exception ex){
                                    result = "获取亚马逊单个店铺["+ jsonObjectOb.get("shopUser").toString()  + "-" + jsonObjectOb.get("shopName").toString() + "]报表信息出错，其中report对象值为"+ JSON.toJSONString(data)+"，具体错误为下载报表文件地址["+url+"]出错";
                                    apiResponse.setCode(400);
                                    apiResponse.setMessage(result);
                                    return apiResponse;
                                }
                            }
                            break;
                        }
                    } else {
                        if (jsonObject.getString("code").equals("429")){
                            Integer redis = 0;
                            if(redisUtil.get(adsReportLog.getReportId())!= null && !redisUtil.get(adsReportLog.getReportId()).equals("")) {
                                redis = Integer.valueOf(redisUtil.get(adsReportLog.getReportId()));
                            }
                            redisUtil.set(adsReportLog.getReportId(),String.valueOf(redis+1000));
                        }else {
                            String errorDescription = jsonObject.getString("message");
                            apiResponse.setCode(400);
                            apiResponse.setMessage("获取亚马逊获取报告失败，具体原因为" + errorDescription);
                            return apiResponse;
                        }
                    }
                } else {
                    apiResponse.setCode(400);
                    apiResponse.setMessage("获取亚马逊获取报告失败！");
                    return apiResponse;
                }
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("获取亚马逊获取报告失败！");
            return apiResponse;
        }
        apiResponse.setCode(0);
        apiResponse.setMessage("获取亚马逊获取报告成功！");
        return apiResponse;
    }


    /**
     * 添加广告活动预算表
     */
    private  ApiResponse addAdsCampaigns(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        try {
            JSONObject jsonObject;
            AdsSpCampaigns adsSpCampaigns;
            List<AdsSpCampaigns> adsSpCampaignsList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpCampaigns = new AdsSpCampaigns();
                adsSpCampaigns.setCampaignId(String.valueOf(jsonObject.get("campaignId")));
                adsSpCampaigns.setCampaignType("商品推广");
                adsSpCampaigns.setCampaignName(String.valueOf(jsonObject.get("campaignName")));
                String campaignStatus = "";
                String campaignStatusJob = String.valueOf(jsonObject.get("campaignStatus"));
                if (campaignStatusJob.equals(CampaignStatusEnum.ENABLED.getCode())) {
                    campaignStatus = CampaignStatusEnum.ENABLED.getName();
                } else if (campaignStatusJob.equals(CampaignStatusEnum.PAUSED.getCode())) {
                    campaignStatus = CampaignStatusEnum.PAUSED.getName();
                } else if (campaignStatusJob.equals(CampaignStatusEnum.ARCHIVED.getCode())) {
                    campaignStatus = CampaignStatusEnum.ARCHIVED.getName();
                } else {
                    campaignStatus = String.valueOf(jsonObject.get("campaignStatus"));
                }
                adsSpCampaigns.setCampaignStatus(campaignStatus);
                adsSpCampaigns.setCampaignBudgetCurrencyCode(String.valueOf(jsonObject.get("campaignBudgetCurrencyCode")));
                adsSpCampaigns.setCampaignBudgetAmount(new BigDecimal(String.valueOf(jsonObject.get("campaignBudgetAmount"))));
                adsSpCampaigns.setCampaignBiddingStrategy(String.valueOf(jsonObject.get("campaignBiddingStrategy")));
                adsSpCampaigns.setImpressions(Integer.valueOf(String.valueOf(jsonObject.get("impressions"))));
                adsSpCampaigns.setClicks(Integer.valueOf(String.valueOf(jsonObject.get("clicks"))));
                adsSpCampaigns.setClickThruRate(new BigDecimal(String.valueOf(jsonObject.get("clickThroughRate") == null ?0:jsonObject.get("clickThroughRate"))));
                adsSpCampaigns.setCost(new BigDecimal(String.valueOf(jsonObject.get("cost"))));
                adsSpCampaigns.setSpend(new BigDecimal(String.valueOf(jsonObject.get("spend"))));
                adsSpCampaigns.setCostPerClick(new BigDecimal(String.valueOf(jsonObject.get("costPerClick") == null ?0:jsonObject.get("costPerClick"))));
                adsSpCampaigns.setUnitsSoldClicks1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldClicks1d"))));
                adsSpCampaigns.setSales1d(new BigDecimal(String.valueOf(jsonObject.get("sales1d"))));
                adsSpCampaigns.setPurchases1d(Integer.valueOf(String.valueOf(jsonObject.get("purchases1d"))));
                adsSpCampaigns.setUnitsSoldSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldSameSku1d"))));
                adsSpCampaigns.setAttributedSalesSameSku1d(new BigDecimal(String.valueOf(jsonObject.get("attributedSalesSameSku1d"))));
                adsSpCampaigns.setPurchasesSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesSameSku1d"))));
                adsSpCampaigns.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpCampaigns.setShopId(jsonObjectOb.get("id").toString());
                adsSpCampaigns.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpCampaigns.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpCampaigns.setDate(String.valueOf(jsonObject.get("date")));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpCampaigns.setCUser(tsUserChange.getUserId());
                adsSpCampaignsList.add(adsSpCampaigns);
            }
            //删除之前的数据
            diySqlMapper.deleteAdsSpCampaigns(jsonObjectOb.get("id").toString(),adsReportLog.getDate());
            //批量添加广告活动预算表
            int adsSpCampaignsListLength = adsSpCampaignsList.size();
            int j = 0;
            while (adsSpCampaignsListLength > 50) {
                diySqlMapper.insertBatchAdsSpCampaigns(adsSpCampaignsList.subList(j, j + 50));
                j = j + 50;
                adsSpCampaignsListLength = adsSpCampaignsListLength - 50;
            }
            if (adsSpCampaignsListLength > 0) {
                diySqlMapper.insertBatchAdsSpCampaigns(adsSpCampaignsList.subList(j, j + adsSpCampaignsListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增广告活动预算失败！失败原因:" + e.getMessage());
        }
        return apiResponse;
    }

    /**
     * 添加广告位报表
     */
    private  ApiResponse addAdsCampaignsPlacement(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        try {
            JSONObject jsonObject;
            AdsSpCampaignsPlacement adsSpCampaignsPlacement;
            List<AdsSpCampaignsPlacement> adsSpCampaignsPlacementList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpCampaignsPlacement = new AdsSpCampaignsPlacement();
                adsSpCampaignsPlacement.setCampaignId(String.valueOf(jsonObject.get("campaignId")));
                adsSpCampaignsPlacement.setCampaignType("商品推广");
                adsSpCampaignsPlacement.setCampaignName(String.valueOf(jsonObject.get("campaignName")));
                String campaignStatus = "";
                String campaignStatusJob = String.valueOf(jsonObject.get("campaignStatus"));
                if (campaignStatusJob.equals(CampaignStatusEnum.ENABLED.getCode())) {
                    campaignStatus = CampaignStatusEnum.ENABLED.getName();
                } else if (campaignStatusJob.equals(CampaignStatusEnum.PAUSED.getCode())) {
                    campaignStatus = CampaignStatusEnum.PAUSED.getName();
                } else if (campaignStatusJob.equals(CampaignStatusEnum.ARCHIVED.getCode())) {
                    campaignStatus = CampaignStatusEnum.ARCHIVED.getName();
                } else {
                    campaignStatus = String.valueOf(jsonObject.get("campaignStatus"));
                }
                adsSpCampaignsPlacement.setCampaignStatus(campaignStatus);
                adsSpCampaignsPlacement.setCampaignBudgetCurrencyCode(String.valueOf(jsonObject.get("campaignBudgetCurrencyCode")));
                adsSpCampaignsPlacement.setCampaignBudgetAmount(new BigDecimal(String.valueOf(jsonObject.get("campaignBudgetAmount"))));
                adsSpCampaignsPlacement.setCampaignBiddingStrategy(String.valueOf(jsonObject.get("campaignBiddingStrategy")));
                adsSpCampaignsPlacement.setImpressions(Integer.valueOf(String.valueOf(jsonObject.get("impressions"))));
                adsSpCampaignsPlacement.setClicks(Integer.valueOf(String.valueOf(jsonObject.get("clicks"))));
                adsSpCampaignsPlacement.setClickThruRate(new BigDecimal(String.valueOf(jsonObject.get("clickThroughRate") == null ?0:jsonObject.get("clickThroughRate"))));
                adsSpCampaignsPlacement.setCost(new BigDecimal(String.valueOf(jsonObject.get("cost"))));
                adsSpCampaignsPlacement.setSpend(new BigDecimal(String.valueOf(jsonObject.get("spend"))));
                adsSpCampaignsPlacement.setCostPerClick(new BigDecimal(String.valueOf(jsonObject.get("costPerClick") == null ?0:jsonObject.get("costPerClick"))));
                adsSpCampaignsPlacement.setUnitsSoldClicks1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldClicks1d"))));
                adsSpCampaignsPlacement.setSales1d(new BigDecimal(String.valueOf(jsonObject.get("sales1d"))));
                adsSpCampaignsPlacement.setPurchases1d(Integer.valueOf(String.valueOf(jsonObject.get("purchases1d"))));
                adsSpCampaignsPlacement.setUnitsSoldSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldSameSku1d"))));
                adsSpCampaignsPlacement.setAttributedSalesSameSku1d(new BigDecimal(String.valueOf(jsonObject.get("attributedSalesSameSku1d"))));
                adsSpCampaignsPlacement.setPurchasesSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesSameSku1d"))));
                adsSpCampaignsPlacement.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpCampaignsPlacement.setShopId(jsonObjectOb.get("id").toString());
                adsSpCampaignsPlacement.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpCampaignsPlacement.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpCampaignsPlacement.setDate(String.valueOf(jsonObject.get("date")));
                adsSpCampaignsPlacement.setPlacementClassification(String.valueOf(jsonObject.get("placementClassification") ==null?null:String.valueOf(jsonObject.get("placementClassification"))));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpCampaignsPlacement.setCUser(tsUserChange.getUserId());
                adsSpCampaignsPlacementList.add(adsSpCampaignsPlacement);
            }
            //删除之前的数据
            diySqlMapper.deleteAdsSpCampaignsPlacement(jsonObjectOb.get("guid").toString(),adsReportLog.getDate());
            //批量添加广告位报表
            int adsSpCampaignsPlacementListListLength = adsSpCampaignsPlacementList.size();
            int j = 0;
            while (adsSpCampaignsPlacementListListLength > 50) {
                diySqlMapper.insertBatchAdsSpCampaignsPlacement(adsSpCampaignsPlacementList.subList(j, j + 50));
                j = j + 50;
                adsSpCampaignsPlacementListListLength = adsSpCampaignsPlacementListListLength - 50;
            }
            if (adsSpCampaignsPlacementListListLength > 0) {
                diySqlMapper.insertBatchAdsSpCampaignsPlacement(adsSpCampaignsPlacementList.subList(j, j + adsSpCampaignsPlacementListListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增广告位报表失败！失败原因:" + e.getMessage());
        }

        return apiResponse;
    }

    /**
     * 添加广告组投放表
     */
    private  ApiResponse addAdsTargeting(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        try {
            JSONObject jsonObject;
            AdsSpTargeting adsSpTargeting;
            List<AdsSpTargeting> adsSpTargetingList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpTargeting = new AdsSpTargeting();
                adsSpTargeting.setPortfolioId(jsonObject.get("portfolioId") == null ?null:String.valueOf(jsonObject.get("portfolioId")));
                adsSpTargeting.setCampaignId(String.valueOf(jsonObject.get("campaignId")));
                adsSpTargeting.setCampaignName(String.valueOf(jsonObject.get("campaignName")));
                adsSpTargeting.setAdGroupId(String.valueOf(jsonObject.get("adGroupId")));
                adsSpTargeting.setAdGroupName(String.valueOf(jsonObject.get("adGroupName")));
                adsSpTargeting.setCampaignBudgetCurrencyCode(String.valueOf(jsonObject.get("campaignBudgetCurrencyCode")));
                adsSpTargeting.setKeywordId(String.valueOf(jsonObject.get("keywordId")));
                adsSpTargeting.setKeyword(String.valueOf(jsonObject.get("keyword")));
                adsSpTargeting.setKeywordType(String.valueOf(jsonObject.get("keywordType")));
                adsSpTargeting.setImpressions(Integer.valueOf(String.valueOf(jsonObject.get("impressions"))));
                adsSpTargeting.setClicks(Integer.valueOf(String.valueOf(jsonObject.get("clicks"))));
                adsSpTargeting.setClickThruRate(new BigDecimal(String.valueOf(jsonObject.get("clickThroughRate") == null ?0:jsonObject.get("clickThroughRate"))));
                adsSpTargeting.setCost(new BigDecimal(String.valueOf(jsonObject.get("cost"))));
                adsSpTargeting.setAcosClicks7d(new BigDecimal(String.valueOf(jsonObject.get("acosClicks7d") == null ?0:jsonObject.get("acosClicks7d"))));
                adsSpTargeting.setRoasClicks7d(new BigDecimal(String.valueOf(jsonObject.get("roasClicks7d") == null ?0:jsonObject.get("roasClicks7d"))));
                adsSpTargeting.setCostPerClick(new BigDecimal(String.valueOf(jsonObject.get("costPerClick") == null ?0:jsonObject.get("costPerClick"))));
                adsSpTargeting.setUnitsSoldClicks1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldClicks1d"))));
                adsSpTargeting.setSales1d(new BigDecimal(String.valueOf(jsonObject.get("sales1d"))));
                adsSpTargeting.setPurchases1d(Integer.valueOf(String.valueOf(jsonObject.get("purchases1d"))));
                adsSpTargeting.setUnitsSoldSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldSameSku1d"))));
                adsSpTargeting.setAttributedSalesSameSku1d(new BigDecimal(String.valueOf(jsonObject.get("attributedSalesSameSku1d"))));
                adsSpTargeting.setPurchasesSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesSameSku1d"))));
                adsSpTargeting.setUnitsSoldOtherSku7d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldOtherSku7d"))));
                adsSpTargeting.setSalesOtherSku7d(new BigDecimal(String.valueOf(jsonObject.get("salesOtherSku7d"))));
                adsSpTargeting.setTopOfSearchImpressionShare(new BigDecimal(String.valueOf(jsonObject.get("topOfSearchImpressionShare") == null ?0:jsonObject.get("topOfSearchImpressionShare"))));
                adsSpTargeting.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpTargeting.setShopId(jsonObjectOb.get("id").toString());
                adsSpTargeting.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpTargeting.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpTargeting.setDate(String.valueOf(jsonObject.get("date")));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpTargeting.setCUser(tsUserChange.getUserId());
                adsSpTargetingList.add(adsSpTargeting);
            }
            //删除之前的数据
            diySqlMapper.deleteAdsTargeting(jsonObjectOb.get("guid").toString(),adsReportLog.getDate());
            //批量添加广告组投放表
            int adsTargetingListLength = adsSpTargetingList.size();
            int j = 0;
            while (adsTargetingListLength > 50) {
                diySqlMapper.insertBatchAdsTargeting(adsSpTargetingList.subList(j, j + 50));
                j = j + 50;
                adsTargetingListLength = adsTargetingListLength - 50;
            }
            if (adsTargetingListLength > 0) {
                diySqlMapper.insertBatchAdsTargeting(adsSpTargetingList.subList(j, j + adsTargetingListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增广告投放报表失败！失败原因:" + e.getMessage());
        }

        return apiResponse;
    }

    /**
     * 添加广告组搜索词表
     */
    private  ApiResponse addAdsSearchTerm(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        try {
            JSONObject jsonObject;
            AdsSpSearchTerm adsSpSearchTerm;
            List<AdsSpSearchTerm> adsSpSearchTermList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpSearchTerm = new AdsSpSearchTerm();
                adsSpSearchTerm.setPortfolioId(jsonObject.get("portfolioId") == null ?null:String.valueOf(jsonObject.get("portfolioId")));
                adsSpSearchTerm.setCampaignId(String.valueOf(jsonObject.get("campaignId")));
                adsSpSearchTerm.setCampaignName(String.valueOf(jsonObject.get("campaignName")));
                adsSpSearchTerm.setAdGroupId(String.valueOf(jsonObject.get("adGroupId")));
                adsSpSearchTerm.setAdGroupName(String.valueOf(jsonObject.get("adGroupName")));
                adsSpSearchTerm.setCampaignBudgetCurrencyCode(String.valueOf(jsonObject.get("campaignBudgetCurrencyCode")));
                adsSpSearchTerm.setSearchTerm(String.valueOf(jsonObject.get("searchTerm")));
                adsSpSearchTerm.setKeywordId(String.valueOf(jsonObject.get("keywordId")));
                adsSpSearchTerm.setKeyword(String.valueOf(jsonObject.get("keyword")));
                adsSpSearchTerm.setKeywordType(String.valueOf(jsonObject.get("keywordType")));
                adsSpSearchTerm.setImpressions(Integer.valueOf(String.valueOf(jsonObject.get("impressions"))));
                adsSpSearchTerm.setClicks(Integer.valueOf(String.valueOf(jsonObject.get("clicks"))));
                adsSpSearchTerm.setClickThruRate(new BigDecimal(String.valueOf(jsonObject.get("clickThroughRate") == null ?0:jsonObject.get("clickThroughRate"))));
                adsSpSearchTerm.setCost(new BigDecimal(String.valueOf(jsonObject.get("cost"))));
                adsSpSearchTerm.setAcosClicks7d(new BigDecimal(String.valueOf(jsonObject.get("acosClicks7d") == null ?0:jsonObject.get("acosClicks7d"))));
                adsSpSearchTerm.setRoasClicks7d(new BigDecimal(String.valueOf(jsonObject.get("roasClicks7d") == null ?0:jsonObject.get("roasClicks7d"))));
                adsSpSearchTerm.setCostPerClick(new BigDecimal(String.valueOf(jsonObject.get("costPerClick") == null ?0:jsonObject.get("costPerClick"))));
                adsSpSearchTerm.setUnitsSoldClicks1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldClicks1d"))));
                adsSpSearchTerm.setSales1d(new BigDecimal(String.valueOf(jsonObject.get("sales1d"))));
                adsSpSearchTerm.setPurchases1d(Integer.valueOf(String.valueOf(jsonObject.get("purchases1d"))));
                adsSpSearchTerm.setUnitsSoldSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldSameSku1d"))));
                adsSpSearchTerm.setAttributedSalesSameSku1d(new BigDecimal(String.valueOf(jsonObject.get("attributedSalesSameSku1d"))));
                adsSpSearchTerm.setPurchasesSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesSameSku1d"))));
                adsSpSearchTerm.setUnitsSoldOtherSku7d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldOtherSku7d"))));
                adsSpSearchTerm.setSalesOtherSku7d(new BigDecimal(String.valueOf(jsonObject.get("salesOtherSku7d"))));
                adsSpSearchTerm.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpSearchTerm.setShopId(jsonObjectOb.get("id").toString());
                adsSpSearchTerm.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpSearchTerm.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpSearchTerm.setDate(String.valueOf(jsonObject.get("date")));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpSearchTerm.setCUser(tsUserChange.getUserId());
                adsSpSearchTermList.add(adsSpSearchTerm);
            }
            //删除之前的数据
            diySqlMapper.deleteSearchTerm(jsonObjectOb.get("guid").toString(),adsReportLog.getDate());
            //批量广告组搜索词表
            int adsSpSearchTermListLength = adsSpSearchTermList.size();
            int j = 0;
            while (adsSpSearchTermListLength > 50) {
                diySqlMapper.insertBatchAdsSearchTerm(adsSpSearchTermList.subList(j, j + 50));
                j = j + 50;
                adsSpSearchTermListLength = adsSpSearchTermListLength - 50;
            }
            if (adsSpSearchTermListLength > 0) {
                diySqlMapper.insertBatchAdsSearchTerm(adsSpSearchTermList.subList(j, j + adsSpSearchTermListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增广告组搜索词表失败 ！失败原因:" + e.getMessage());
        }

        return apiResponse;
    }

    /**
     * 添加广告商品表
     */
    private  ApiResponse addAdsAdvertisedProduct(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        AdsSpAdvertisedProduct adsSpAdvertisedProduct;
        List<AdsSpAdvertisedProduct> adsSpAdvertisedProductList = new ArrayList<>();
        try {
            JSONObject jsonObject;
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpAdvertisedProduct = new AdsSpAdvertisedProduct();
                adsSpAdvertisedProduct.setPortfolioId(jsonObject.get("portfolioId") == null ?null:String.valueOf(jsonObject.get("portfolioId")));
                adsSpAdvertisedProduct.setCampaignId(String.valueOf(jsonObject.get("campaignId")));
                adsSpAdvertisedProduct.setCampaignName(String.valueOf(jsonObject.get("campaignName")));
                adsSpAdvertisedProduct.setAdGroupId(String.valueOf(jsonObject.get("adGroupId")));
                adsSpAdvertisedProduct.setAdGroupName(String.valueOf(jsonObject.get("adGroupName")));
                adsSpAdvertisedProduct.setCampaignBudgetCurrencyCode(String.valueOf(jsonObject.get("campaignBudgetCurrencyCode")));
                adsSpAdvertisedProduct.setAdId(String.valueOf(jsonObject.get("adId")));
                adsSpAdvertisedProduct.setAdvertisedAsin(String.valueOf(jsonObject.get("advertisedAsin")));
                adsSpAdvertisedProduct.setAdvertisedSKU(String.valueOf(jsonObject.get("advertisedSku")));
                //查询商品编码
                List<Map<String, Object>> amazonShopProductList = new TpAmazonShopProduct()
                        .addLeftJoin("TP_ProductActive t2 on A.code = t2.code")
                        .addField("t2.name as name,t2.vSfJp as vSfJp")
                        .where("A.shopId = '" + jsonObjectOb.get("id").toString() + "' AND A.SellerSku = '" + adsSpAdvertisedProduct.getAdvertisedSKU() + "' " +
                                "AND A.Asin = '"  + adsSpAdvertisedProduct.getAdvertisedAsin() + "'")
                        .queryMap();
                TpAmazonShopExchangeRate tpAmazonShopExchangeRate = new TpAmazonShopExchangeRate().where("A.Code = '" + jsonObject.get("campaignBudgetCurrencyCode") + "'").queryFirst();
                if (tpAmazonShopExchangeRate != null){
                    adsSpAdvertisedProduct.setExchangeRate(tpAmazonShopExchangeRate.getExchangeRate1());
                }
                if (amazonShopProductList != null && amazonShopProductList.size() > 0) {
                    Map<String, Object> amazonShopProduct = amazonShopProductList.get(0);
                    adsSpAdvertisedProduct.setProductCode(String.valueOf(amazonShopProduct.get("code")));
                    adsSpAdvertisedProduct.setProductName(amazonShopProduct.get("name") == null ? null :String.valueOf(amazonShopProduct.get("name")));
                    adsSpAdvertisedProduct.setVSfJp(amazonShopProduct.get("vSfJp") == null ? null :String.valueOf(amazonShopProduct.get("vSfJp")));
                }
                adsSpAdvertisedProduct.setImpressions(Integer.valueOf(String.valueOf(jsonObject.get("impressions"))));
                adsSpAdvertisedProduct.setClicks(Integer.valueOf(String.valueOf(jsonObject.get("clicks"))));
                adsSpAdvertisedProduct.setClickThruRate(new BigDecimal(String.valueOf(jsonObject.get("clickThroughRate") == null ?0:jsonObject.get("clickThroughRate"))));
                adsSpAdvertisedProduct.setCost(new BigDecimal(String.valueOf(jsonObject.get("cost"))));
                adsSpAdvertisedProduct.setSpend(new BigDecimal(String.valueOf(jsonObject.get("spend"))));
                adsSpAdvertisedProduct.setAcosClicks7d(new BigDecimal(String.valueOf(jsonObject.get("acosClicks7d") == null ?0:jsonObject.get("acosClicks7d"))));
                adsSpAdvertisedProduct.setRoasClicks7d(new BigDecimal(String.valueOf(jsonObject.get("roasClicks7d") == null ?0:jsonObject.get("roasClicks7d"))));
                adsSpAdvertisedProduct.setCostPerClick(new BigDecimal(String.valueOf(jsonObject.get("costPerClick") == null ?0:jsonObject.get("costPerClick"))));
                adsSpAdvertisedProduct.setUnitsSoldClicks1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldClicks1d"))));
                adsSpAdvertisedProduct.setSales1d(new BigDecimal(String.valueOf(jsonObject.get("sales1d"))));
                adsSpAdvertisedProduct.setPurchases1d(Integer.valueOf(String.valueOf(jsonObject.get("purchases1d"))));
                adsSpAdvertisedProduct.setUnitsSoldSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldSameSku1d"))));
                adsSpAdvertisedProduct.setAttributedSalesSameSku1d(new BigDecimal(String.valueOf(jsonObject.get("attributedSalesSameSku1d"))));
                adsSpAdvertisedProduct.setPurchasesSameSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesSameSku1d"))));
                adsSpAdvertisedProduct.setUnitsSoldOtherSku7d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldOtherSku7d"))));
                adsSpAdvertisedProduct.setSalesOtherSku7d(new BigDecimal(String.valueOf(jsonObject.get("salesOtherSku7d"))));
                adsSpAdvertisedProduct.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpAdvertisedProduct.setShopId(jsonObjectOb.get("id").toString());
                adsSpAdvertisedProduct.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpAdvertisedProduct.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpAdvertisedProduct.setDate(String.valueOf(jsonObject.get("date")));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpAdvertisedProduct.setCUser(tsUserChange.getUserId());
                adsSpAdvertisedProductList.add(adsSpAdvertisedProduct);
            }
            //删除之前的数据
            diySqlMapper.deleteSpAdvertisedProduct(jsonObjectOb.get("guid").toString(),adsReportLog.getDate());
            //批量添加广告商品表
            int adsSpAdvertisedProductListLength = adsSpAdvertisedProductList.size();
            int j = 0;
            while (adsSpAdvertisedProductListLength > 50) {
                diySqlMapper.insertBatchSpAdvertisedProduct(adsSpAdvertisedProductList.subList(j, j + 50));
                j = j + 50;
                adsSpAdvertisedProductListLength = adsSpAdvertisedProductListLength - 50;
            }
            if (adsSpAdvertisedProductListLength > 0) {
                diySqlMapper.insertBatchSpAdvertisedProduct(adsSpAdvertisedProductList.subList(j, j + adsSpAdvertisedProductListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增广告商品表失败！失败原因:" + e.getMessage());
        }
        return apiResponse;
    }

    /**
     * 非广告商品订单情况表
     */
    private  ApiResponse addAdsPurchasedProduct(JSONArray jsonArray,ApiResponse apiResponse ,JSONObject jsonObjectOb,AdsReportLog adsReportLog, ThrOperateCompanyApply thrOperateCompanyApply){
        try {
            JSONObject jsonObject;
            AdsSpPurchasedProduct adsSpPurchasedProduct;
            List<AdsSpPurchasedProduct> adsSpPurchasedProductList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = JSONObject.parseObject(String.valueOf(jsonArray.get(i)));
                adsSpPurchasedProduct = new AdsSpPurchasedProduct();
                adsSpPurchasedProduct.setAdGroupId(String.valueOf(jsonObject.get("adGroupId")));
                adsSpPurchasedProduct.setAdvertisedSKU(String.valueOf(jsonObject.get("advertisedSku")));
                adsSpPurchasedProduct.setPurchasedAsin(String.valueOf(jsonObject.get("purchasedAsin")));
                adsSpPurchasedProduct.setUnitsSoldOtherSku1d(Integer.valueOf(String.valueOf(jsonObject.get("unitsSoldOtherSku1d"))));
                adsSpPurchasedProduct.setSalesOtherSku1d(new BigDecimal(String.valueOf(jsonObject.get("salesOtherSku1d"))));
                adsSpPurchasedProduct.setPurchasesOtherSku1d(Integer.valueOf(String.valueOf(jsonObject.get("purchasesOtherSku1d"))));
                adsSpPurchasedProduct.setShopNameMc(jsonObjectOb.get("shopName").toString());
                adsSpPurchasedProduct.setShopId(jsonObjectOb.get("id").toString());
                adsSpPurchasedProduct.setVGsJc(jsonObjectOb.get("vgsjc").toString());
                adsSpPurchasedProduct.setVGsBm(jsonObjectOb.get("vgsbm").toString());
                adsSpPurchasedProduct.setDate(String.valueOf(jsonObject.get("date")));
                TsUserChange tsUserChange = new TsUserChange().setId(thrOperateCompanyApply.getOperatorChangeId()).queryFirst();
                if(tsUserChange!=null)adsSpPurchasedProduct.setCUser(tsUserChange.getUserId());
                adsSpPurchasedProduct.setAdvertisedAsin(String.valueOf(jsonObject.get("advertisedAsin")));
                adsSpPurchasedProductList.add(adsSpPurchasedProduct);
            }
            //删除之前的数据
            diySqlMapper.deleteSpPurchasedProduct(jsonObjectOb.get("guid").toString(),adsReportLog.getDate());
            //批量非广告商品订单情况表
            int adsSpPurchasedProductListLength = adsSpPurchasedProductList.size();
            int j = 0;
            while (adsSpPurchasedProductListLength > 50) {
                diySqlMapper.insertBatchSpPurchasedProduct(adsSpPurchasedProductList.subList(j, j + 50));
                j = j + 50;
                adsSpPurchasedProductListLength = adsSpPurchasedProductListLength - 50;
            }
            if (adsSpPurchasedProductListLength > 0) {
                diySqlMapper.insertBatchSpPurchasedProduct(adsSpPurchasedProductList.subList(j, j + adsSpPurchasedProductListLength));
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("新增非广告商品订单情况表失败！失败原因:" + e.getMessage());
        }

        return apiResponse;
    }

    @Override
    public ApiResponse getSynchronousAdId(){
        ApiResponse apiResponse = new ApiResponse();
        try {
            List<AdsSpPurchasedProduct> adsSpPurchasedProductList = new AdsSpPurchasedProduct()
                    .where("A.AdvertisedProductId IS NULL")
                    .queryList();
            for (AdsSpPurchasedProduct adsSpPurchasedProduct : adsSpPurchasedProductList) {
                //查询广告商品表
                AdsSpAdvertisedProduct adsSpAdvertisedProduct = new AdsSpAdvertisedProduct()
                        .where("A.adGroupId = '" +adsSpPurchasedProduct.getAdGroupId() + "' AND A.advertisedSku = '" + adsSpPurchasedProduct.getAdvertisedSKU() + "'")
                        .queryFirst();
                if (adsSpAdvertisedProduct != null) {
                    adsSpPurchasedProduct.setProductCode(adsSpAdvertisedProduct.getProductCode());
                    adsSpPurchasedProduct.setProductName(adsSpAdvertisedProduct.getProductName());
                    adsSpPurchasedProduct.setAdvertisedProductId(String.valueOf(adsSpAdvertisedProduct.getId()));
                    adsSpPurchasedProductMapper.update(adsSpPurchasedProduct);
                }
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("每日定时同步非广告商品订单的广告id失败！失败原因:" + e.getMessage());
        }
        return apiResponse;
    }
}
